package com.qiaofang.applet.common.util;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.UrlSafeBase64;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @Author: youqing.yang
 * @Create: 2021/03/26 11:10
 * @Description:
 **/
@Slf4j
public class QiNiuUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    //文字水印处理
    public static String watermarkSynthesisText(String photoURL, String text) {

        //由于文件名可能带有中文，所以先转换一下
        if(StringUtils.isNotBlank(photoURL) && StringUtils.lastIndexOf(photoURL,"/") != -1){
            int one = photoURL.lastIndexOf("/");
            String str = photoURL.substring((one+1));
            photoURL = StringUtils.replace(photoURL,str, URLEncoder.encode(str));
        }
        //图片信息
        JSONObject jsonObject = null;
        try {
            URI uri = URI.create(photoURL + "?imageInfo");
            jsonObject = restTemplate.getForObject(uri, JSONObject.class);
        } catch (RestClientException e) {
            log.info("七牛获取文件信息出错 url=" + photoURL + "?", e);
        }
        int width = 0;
        int height = 0;
        Boolean flag = false;
        if (jsonObject == null){
            //这里再请求一次
            try {
                BufferedImage bufferedImage = ImageIO.read(new URL(photoURL));
                width = bufferedImage.getWidth();
                height = bufferedImage.getHeight();
                flag = true;
                log.info("width:{},height:{},jsonObject:{}", width, height, jsonObject);
            } catch (Exception e) {
                log.info("通过IO方式获取图片信息失败 url=" + photoURL + "?", e);
            }
            if (flag){
                int maxLength = width > height ? width : height;
                BigDecimal big = new BigDecimal(maxLength);
                return photoURL +
                        "?watermark/4" +
                        "/text/" + UrlSafeBase64.encodeToString(text) + "" +
                        "/fill/" + UrlSafeBase64.encodeToString("#FFFFFF") +
                        "/rotate/-45" +
                        "/dissolve/30" +
                        "/fontsize/" + maxLength +
                        "/uw/" + (big.divide(new BigDecimal(4), BigDecimal.ROUND_UP).intValue()) +
                        "/uh/" + (big.divide(new BigDecimal(4), BigDecimal.ROUND_UP).intValue());
            }
            return photoURL;
        }

        int photoWidth = jsonObject.get("width") != null ? Integer.parseInt(jsonObject.get("width").toString()) : 2000;
        int photoHeight = jsonObject.get("height") != null ? Integer.parseInt(jsonObject.get("height").toString()) : 2000;
        int maxLength = photoWidth > photoHeight ? photoWidth : photoHeight;
        BigDecimal big = new BigDecimal(maxLength);
        //这里采用的文字水印是铺满的格式，不用文字位置
        return photoURL +
                "?watermark/4" +
                "/text/" + UrlSafeBase64.encodeToString(text) + "" +
                "/fill/" + UrlSafeBase64.encodeToString("#FFFFFF") +
                "/rotate/-45" +
                "/dissolve/30" +
                "/fontsize/" + maxLength +
                "/uw/" + (big.divide(new BigDecimal(4), BigDecimal.ROUND_UP).intValue()) +
                "/uh/" + (big.divide(new BigDecimal(4), BigDecimal.ROUND_UP).intValue());
    }

    //图片水印处理
    public static String watermarkSynthesis(String imageUrl, String watermarkUrl, String gravity) {
//        String infoTye = "imageInfo";

//        Map watermarkInfo = getFileInfo(watermarkUrl, infoTye);
//        //水印宽度
//        int wwidth = Integer.valueOf(watermarkInfo.get("width").toString());
//        //水印高度
//        int wheight = Integer.valueOf(watermarkInfo.get("height").toString());
//
//        Map jsonObject = getFileInfo(watermarkUrl, infoTye);
//        //水印宽度
//        int photoWidth = Integer.valueOf(jsonObject.get("width").toString());
//        //水印高度
//        int photoHeight = Integer.valueOf(jsonObject.get("height").toString());
//
//        float time=0f;
//        //取水印和图片宽度比和高度比最大的一个。确保水印能被压缩的宽和高都比图片小
//        time= ((float)wwidth)/(photoWidth)>((float)wheight)/(photoHeight)?
//                ((float)wwidth)/(photoWidth):
//                ((float)wheight)/(photoHeight);
//        String scaleStr = "0.2";
//        float scale = 0.0f;
//        try{
//            scale = Float.valueOf(scaleStr);
//        }catch (Exception e){
//            scale = 0.2f;
//        }
//        //计算水印图片缩放大小
//        int percent=(int)(100*scale/time);
//        percent=percent<1?1:percent;
//        //七牛图片压缩范围1-1000%，只能为整数，且不能为1000%. 超过100为放大 压缩后的水印大约为图片的90%即可
//        percent=percent>999?999:percent;
//        watermarkUrl = watermarkUrl+"?imageMogr2/thumbnail/!"+percent+"p";
//        Map imageInfo = getFileInfo(imageUrl, infoTye);
//        //水印宽度
//        int photoWidth = Integer.valueOf(imageInfo.get("width").toString());
//        //水印高度
//        int photoHeight = Integer.valueOf(imageInfo.get("height").toString());
//        int maxLength = photoWidth > photoHeight ? photoWidth : photoHeight;
//        watermarkUrl = (maxLength/9);
        //加密
        String encodeUrl = UrlSafeBase64.encodeToString(watermarkUrl);
        String returnUrl = imageUrl + "?imageMogr2/strip|watermark/1" +
                "/image/" + encodeUrl +
                "/dissolve/100" +
                "/gravity/" + gravity +
                "/dx/20" +
                "/dy/20" +
                "/dissolve/60" +
                "/ws/0.25";
        return returnUrl;
    }
}
